/* eslint-disable vue/valid-v-else */
/* eslint-disable vue/valid-template-root */

<template>
 <div class="image-container">
    <el-card class="box-card">
      <div slot="header">
       <el-breadcrumb separator-class="el-icon-arrow-right">
          <el-breadcrumb-item :to="{ path: '/' }">首页</el-breadcrumb-item>
          <el-breadcrumb-item>内容管理</el-breadcrumb-item>
        </el-breadcrumb>
      </div>
      <div style="padding-bottom: 20px;">
        <el-radio-group v-model="isCollected" size="mini" @change="hSwitchCollect">
          <el-radio-button label="全部"></el-radio-button>
          <el-radio-button label="收藏"></el-radio-button>
        </el-radio-group>

        <el-button style="float:right;" type="success" size="mini" @click="qingkong" >
            上传图片
        </el-button>
      </div>
      <!-- 素材列表 -->
      <el-row :gutter="10">
        <el-col
          v-for="image in images"
          :key="image.id"
          class="img_item" :span="4">
          <el-image
            style="height: 180px;width: 180px"
            :src="image.url"
            fit="cover"
          ></el-image>
          <div class="option">
            <span class="el-icon-star-off" :class="{red:image.is_collected}" @click="hSwitchCollectImage(image)" ></span>
            <span class="el-icon-delete" @click="hDelete(image)" ></span>
          </div>
        </el-col>
      </el-row>
       <!-- 分页 -->
      <el-pagination
        background
        layout="prev, pager, next"
        :page-size="10"
        @current-change="hCurrentChange"
        :total="total_count">
      </el-pagination>
    </el-card>

     <el-dialog
        append-to-body
        title="提示"
        :visible.sync="dialogVisible"
        width="30%">
        <el-upload
            class="avatar-uploader"
            action="http://api-toutiao-web.itheima.net/mp/v1_0/user/images"
            :headers="headers"
            name="image"
            :show-file-list="false"
            :on-success="handleAvatarSuccess"
            :before-upload="beforeAvatarUpload">
            <!-- <img v-if="imageUrl" :src="imageUrl" class="avatar"> -->
            <el-image v-if="imageUrl" :src="imageUrl" class="avatar" @load="hImageLoad"/>
            <i v-else class="el-icon-plus avatar-uploader-icon"></i>
        </el-upload>
      </el-dialog>
  </div>
</template>

<script>
export default {
  name: 'images',
  data () {
    return {
      headers: {
        Authorization: `Bearer ${localStorage.getItem('tokenStr')}`
      },
      imageUrl: '',
      dialogVisible: false,
      page: 1,
      total_count: 0,
      isCollected: '全部',
      images: []
    //   isCollapsed: true
    }
  },
  created () {
    this.loadImages()
  },
  methods: {
    // 删除图片功能
    async  doDelete (image) {
      try {
        const res = await this.$axios({
          url: '/mp/v1_0/user/images/' + image.id,
          method: 'DELETE'
        })
        console.log(res)
        this.$message.success('删除成功')
        this.loadImages()
      } catch (err) {
        console.log(err)
      }
    },
    hDelete (image) {
      this.$confirm('你确定要删除吗？').then(() => {
        this.doDelete(image)
      }).catch(() => {})
    },
    // 取消收藏功能
    async  hSwitchCollectImage (image) {
      try {
        const res = await this.$axios({
          url: '/mp/v1_0/user/images/' + image.id,
          method: 'PUT',
          data: {
            collect: !image.is_collected // 取反
          }
        })
        console.log(res)
        this.$message.success('操作成功')
        image.is_collected = !image.is_collected
      } catch (err) {
        console.log(err)
        this.$message.error('操作失败')
      }
    },
    //   清空
    qingkong () {
      this.dialogVisible = true
      this.imageUrl = ''
    },
    //   收藏全部切换
    hSwitchCollect () {
      this.page = 1
      this.loadImages()
    },
    hCurrentChange (curPage) {
      this.page = curPage
      this.loadImages()
    },
    buildParams () {
      // 封装方法获取参数
      const paramObj = {
        page: this.page,
        per_page: 10,
        collect: this.isCollected === '收藏'
      }
      return paramObj
    },
    async loadImages () {
      try {
        const params = this.buildParams()
        const res = await this.$axios({
          method: 'GET',
          url: '/mp/v1_0/user/images',
          params
        })
        this.images = res.data.data.results
        this.total_count = res.data.data.total_count
        console.log(res)
      } catch (err) {
        console.log(err)
      }
    },
    // 自动消失
    hImageLoad () {
      setTimeout(() => {
        this.dialogVisible = false
        this.loadImages()
      }, 1000)
    },
    handleAvatarSuccess (res, file) {
      this.$message.success('上传成功')
      this.imageUrl = URL.createObjectURL(file.raw)
    },
    // 图片的格式和大小
    beforeAvatarUpload (file) {
      const isJPG = file.type === 'image/jpeg'
      const isLt2M = file.size / 1024 / 1024 < 2

      if (!isJPG) {
        this.$message.error('上传头像图片只能是 JPG 格式!')
      }
      if (!isLt2M) {
        this.$message.error('上传头像图片大小不能超过 2MB!')
      }
      return isJPG && isLt2M
    }
  }
}
</script>

<style lang="less" scoped>
  .img_item {
    position: relative;
    box-sizing: border-box;
  }
  .option {
    position: absolute;
    left: 5px;
    width:180px;
    bottom: 5px;
    height: 30px;
    line-height: 30px;
    background: rgba(0, 0, 0, 0.3);
    text-align: center;
    color: #fff;
    span {
      margin: 0 30px;
      cursor: pointer;
    }
  }
.avatar-uploader {
    text-align: center;
}
.avatar-uploader-icon {
    font-size: 28px;
    color: #8c939d;
    width: 178px;
    height: 178px;
    line-height: 178px;
    text-align: center;
}
.avatar-uploader /deep/ .el-upload {
    border: 1px dashed #d9d9d9;
    border-radius: 6px;
    cursor: pointer;
    position: relative;
    overflow: hidden;
}
.red {
    color: red;
}
  /deep/ .el-upload {
    border: 1px dashed #d9d9d9;
    border-radius: 6px;
    cursor: pointer;
    position: relative;
    overflow: hidden;
  }
  .avatar-uploader .el-upload:hover {
    border-color: #409EFF;
  }
  .avatar-uploader-icon {
    font-size: 28px;
    color: #8c939d;
    width: 178px;
    height: 178px;
    line-height: 178px;
    text-align: center;
  }
  .avatar {
    width: 178px;
    height: 178px;
    display: block;
  }
</style>
